#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
typedef struct point
{
    int x;
    int y;
    point(int a,int b)
    {
        x=a;
        y=b;
    }
}point;
vector<point> house;
vector<point> people;
int N,M;
int map[110][110];
int link[110];
bool visit[110];
bool dfs(int vs)
{
    int i;
    for(i=0;i<house.size();i++)
    {
        if(!visit[i])
        {
            visit[i]=true;
            if(!link[i]||map[vs][i]<=map[link[i]][i]&&(dfs(link[i])))
            {
                link[i]=vs;
                return true;
            }
        }
    }
    return false;
}
int main()
{
    int i,j,res;
    char c;
    while(1)
    {
        cin>>N>>M;
        if(!N&&!M) break;
        getchar();
        fill(link,link+110,0);
        for(i=1;i<=N;i++)
        {
            for(j=1;j<=M;j++)
            {
                c=getchar();
                if(c=='m')
                {
                    people.push_back(point(i,j));
                }
                else if(c=='H')
                {
                    house.push_back(point(i,j));
                }
            }
            getchar();
        }
        for(i=0;i<people.size();i++)
        {
            for(j=0;j<house.size();j++)
            {
                  map[i][j]=abs(people[i].x-house[j].x)+abs(people[i].y-house[j].y);
            }
        }
        for(i=0;i<people.size();i++)
        {
            fill(visit,visit+110,0);
            dfs(i);
        }
        for(i=0,res=0;i<house.size();i++)
        {
            res+=map[link[i]][i];
        }
        cout<<res<<endl;
    }
    return 0;
}
